package com.hp.springioc04;

import java.lang.reflect.Field;

/**
 * 电脑工厂
 */
public class ComputerFactory {
    public static Computer createComputer() throws IllegalAccessException, InstantiationException {
        //获得Computer的class
        Class<Computer> computerClass = Computer.class;
        //创建对象
        Computer obj = computerClass.newInstance();
        //获得所有的属性
        Field[] fields = computerClass.getDeclaredFields();
        for(Field field : fields){
            //读取属性上的注解
            MyValue myValue = field.getDeclaredAnnotation(MyValue.class);
            //修改访问修饰符为public
            field.setAccessible(true);
            //判断有MyValue注解
            if(myValue != null){
                //读取value值
                String value = myValue.value();
                //设置值
                field.set(obj,value);
            }
            MyComponent myComponent = field.getDeclaredAnnotation(MyComponent.class);
            if(myComponent != null){
                //读取类型，创建属性的对象
                Class value = myComponent.value();
                Object o = value.newInstance();
                field.set(obj,o);
            }
        }
        return obj;
    }
}
